package nowcoder.offer;

/**
 * 序列化与反序列化二叉树
 *
 * @author briarbear
 * @blog https://briarbear.github.io
 * @date 2018-08-30 10:53
 */
public class SerializeTree {
    public int index = -1;
    /**
     * 前序遍历做序列化
     */
    String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        if (root == null){
            sb.append("# ");
            return sb.toString();
        }
        sb.append(root.val + " ");
        sb.append(serialize(root.left));
        sb.append(serialize(root.right));
        return sb.toString();
    }


    TreeNode deserialize(String str) {
        index++;
        int len = str.length();
        if (index >= len) return null;

        String[] ss = str.split(" ");
        TreeNode node = null;
        if (!ss[index].equals("#")){
            node = new TreeNode(Integer.valueOf(ss[index]));
            node.left = deserialize(str);
            node.right = deserialize(str);
        }
        return node;
    }
}
